package com.bbx.flink.demo.data_stream_state.functions;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * 前后数值超差超过5   将前后数值返回
 */
@Slf4j
public class MapStateDemo  extends RichFlatMapFunction<Integer, Map<String ,Integer>> {
    private static final long serialVersionUID = 6134886314143779698L;


    private MapState<String,Integer> mapState;


    @Override
    public void open(Configuration parameters) throws Exception {
       mapState = getRuntimeContext().getMapState(
               new MapStateDescriptor("MapState", String.class, Integer.class)
       );
    }

    @Override
    public void flatMap(Integer value, Collector<Map<String, Integer>> out) throws Exception {
        Integer oldTemp=0;
        HashMap<String, Integer> resMap = new HashMap<>();
        if (mapState.contains("temp")) {
            oldTemp = mapState.get("temp");
            int i = value - oldTemp >= 0 ? value - oldTemp : oldTemp - value;
            log.info("~~~~~~~~~~~~~~~~~~~~~~~数据差值为[{}]",i);
            if(i>5){
                resMap.put("oldTemp" ,oldTemp);
                resMap.put("currentTemp" ,value);
                out.collect(resMap);
            }
        }
        mapState.put("temp",value);
    }
}
